use crate::process::{Process, ProcessState};
use core::arch::asm;

pub struct Scheduler {
    processes: [Option<Process>; 16],
    current_process: usize,
    process_count: usize,
}

impl Scheduler {
    pub fn new() -> Self {
        Scheduler {
            processes: [None; 16],
            current_process: 0,
            process_count: 0,
        }
    }

    pub fn add_process(&mut self, mut process: Process) {
        if self.process_count < self.processes.len() {
            process.init_stack();
            self.processes[self.process_count] = Some(process);
            self.process_count += 1;
        }
    }

    pub fn schedule(&mut self) -> Option<&mut Process> {
        if self.process_count == 0 {
            return None;
        }

        // 循环查找下一个就绪进程
        let mut tries = 0;
        while tries < self.process_count {
            self.current_process = (self.current_process + 1) % self.process_count;
            // 先判断状态，避免过早可变借用
            if self.processes[self.current_process].as_ref().map_or(false, |p| p.state == ProcessState::Ready) {
                return self.processes[self.current_process].as_mut();
            }
            tries += 1;
        }

        None
    }

    pub fn get_current_process(&mut self) -> Option<&mut Process> {
        if self.process_count > 0 {
            self.processes[self.current_process].as_mut()
        } else {
            None
        }
    }
}